package com.cypher.encryptionanddecryption.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.MainActivity;
import com.cypher.encryptionanddecryption.adapter.BluetoothTalkAdapter;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothManagerSingleton;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.watcher.CustomTextHexWatcher;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 蓝牙通信界面
 * @author: 古霸天
 * @date: 2020/11/9
 */
public class BluetoothTalkFragment extends Fragment {
    private Button sendBtn;
    private Button scanBtn;
    private EditText talkContent;
    private ListView talkList;
    private BluetoothTalkAdapter talkAdapter;
    private BluetoothGattManager gattManager;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bluetooth_talk, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        talkContent = view.findViewById(R.id.talk_content);
        // 设置输入框只能输入hex码
        talkContent.addTextChangedListener(new CustomTextHexWatcher(talkContent));
//        // 设置为多文本编辑框
//        talkContent.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
//        // 设置单行为false
//        talkContent.setSingleLine(false);
//        // 设置水平滚动为false
//        talkContent.setHorizontallyScrolling(false);

        // 初始化列表
        talkList = view.findViewById(R.id.bluetooth_talk_list);
        // 创建列表适配器
        talkAdapter =  new BluetoothTalkAdapter(view.getContext());
        // 初始化适配器数据集合
        List<String> contents = new ArrayList<>();
        talkAdapter.setContents(contents);
        talkAdapter.notifyDataSetChanged();
        talkList.setAdapter(talkAdapter);

        // 获取蓝牙管理类
        gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();
        setGattManagerField();

        initSendBtn(view);

        initScanBtn(view);
    }

    /**
     * 初始化发送按钮及其点击事件
     * @param view
     */
    private void initSendBtn(View view) {
        sendBtn = view.findViewById(R.id.content_send_btn);
        View.OnClickListener sendBtnClick = (v) -> {
            // 判断为空，再获取一次，以防切换fragment时未连接
            if (gattManager == null) {
                gattManager = BluetoothManagerSingleton.getInstance().getBluetoothGattManager();
            }
            // 未连接过蓝牙，或者断开蓝牙
            if (gattManager == null || !gattManager.isGattConnected()) {
                Toast.makeText(BluetoothManagerSingleton.getInstance().getActivity(), "请先连接蓝牙", Toast.LENGTH_LONG).show();
                return;
            }

            setGattManagerField();

            // 获取输入框内容
            String content = talkContent.getText().toString();
            if (StringUtils.isEmpty(content)) {
                Toast.makeText(BluetoothManagerSingleton.getInstance().getActivity(), "请输入需要发送的数据", Toast.LENGTH_LONG).show();
                return;
            }
            // 清空输入框内容
            talkContent.setText("");
            // 向列表中插入数据
            gattManager.addList("<- " + content);
            // 向硬件设备发送数据
            gattManager.sendMsg(HexUtils.hexToBytes(content));

        };
        sendBtn.setOnClickListener(sendBtnClick);
    }

    /**
     *  如果蓝牙连接管理类以及属性talkList、talkAdapter不为空的时候
     *  存放ListView，Adapter到蓝牙管理类
     */
    private void setGattManagerField() {
        if (gattManager != null) {

            if (gattManager.getTalkList() == null)
                gattManager.setTalkList(talkList);

            if (gattManager.getTalkAdapter() == null)
                gattManager.setTalkAdapter(talkAdapter);

        }
    }

    /**
     * 初始化扫描条形码按钮
     * @param view
     */
    private void initScanBtn(View view) {
        scanBtn = view.findViewById(R.id.content_scan_btn);
        // 扫描按钮点击事件
        View.OnClickListener scanClick = (v) -> {
            MainActivity mainActivity = (MainActivity) BluetoothManagerSingleton.getInstance().getActivity();
//            mainActivity.zxingScan(talkContent);
            Toast.makeText(mainActivity, "此功能暂未开发", Toast.LENGTH_LONG).show();
        };
        // 添加监听
        scanBtn.setOnClickListener(scanClick);
    }
}
